﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using ARchGL.Declaration.Platform.Domain.Entities;
using ARchGL.Declaration.Platform.Service.Dtos;
using ARchGL.Declaration.Platform.Service.EventHandles;
using log4net;
using RestSharp;
using TDF.Core.Log;

namespace ARchGL.Declaration.Platform.Service
{
    /// <summary>
    /// 自动任务
    /// </summary>
    public class AutoTaskService : IAutoTaskService
    {
        #region 注入服务

        /// <summary>
        /// 
        /// </summary>
        public ILog Log => LogFactory.GetLogger(GetType());
        private IPushService pushService;
        private ISystemService systemService;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="_pushService"></param>
        /// <param name="_systemService"></param>
        public AutoTaskService(IPushService _pushService, ISystemService _systemService)
        {
            pushService = _pushService;
            systemService = _systemService;
        }

        #endregion

        /// <summary>
        /// 开始自动任务
        /// </summary>
        public void StartTask()
        {
            RetryPushDataTask();
            ClearExpireSessionTask();//自动清理过期 Session
        }

        #region 千变数据重新推送失败数据（每小时一次）

        private void RetryPushDataTask()
        {
            var thread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        var list = pushService.GetPushPagedList(new PushProjectHistoryCriteria
                        {
                            PageIndex = 1,
                            PageSize = 100,
                            Status = PushStatus.失败,
                        }).Item2.Rows.ToList();

                        if (list.Count > 0)
                        {
                            var historyList = new List<Push_Project_History>();

                            foreach (var item in list)
                            {
                                var request = new RestRequest(item.Url, Method.POST);
                                var responsePost = BaseMethod.ExecuteRequest(request, item.Data);

                                if (responsePost.StatusCode == HttpStatusCode.OK)
                                    item.Status = PushStatus.成功;

                                item.Count += 1;
                                if (!string.IsNullOrWhiteSpace(responsePost.Content))
                                    item.Message = responsePost.Content;
                                historyList.Add(item);
                            }
                            pushService.UpdateStatus(historyList);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("重新推送数据异常", ex);//记录日志，继续尝试运行
                    }
                    Thread.Sleep(TimeSpan.FromHours(1));
                }
            })
            { IsBackground = true };
            thread.Start();
        }

        #endregion

        #region 清除过期 Session

        /// <summary>
        /// 自动清理过期 Session
        /// </summary>
        private void ClearExpireSessionTask()
        {
            var thread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        //确保每天只运行一次
                        if (DateTime.Now.Hour == 2 && DateTime.Now.Minute == 1)
                        {
                            systemService.ClearExpireSession();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("清理过期 Session 异常", ex);//记录日志，继续尝试运行
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(50));
                }
            })
            { IsBackground = true };
            thread.Start();
        }

        #endregion
    }
}
